package com.heima.article.interceptor;

import com.heima.utils.thread.ApThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 陈辉
 * @data 2024 16:16
 */
@Component
public class ArticleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 解析请求头，拿到userId，存入ThreadLocal
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            ApThreadLocalUtil.set(Integer.valueOf(userId));
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal: 这里一定要及时清理，否则会存在服务器内存溢出的风险
        ApThreadLocalUtil.clear();
    }
}
